var Scale = requirePlugin("ykb_measure_plugin")
const app = getApp()

Page({
  data: {
    realTimeWeight: 0,
    bleState: "空闲",
    state: "paused",
    measureData: null,
    score: 0,
    list: [],
    available: false,
    discovering: false,
    connected: false,
    unit: 'kg'
  },
  connect(e) {
    let id = e.target.dataset.id
    let device = this.data.list[id]
    
    Scale.createConnect(device).then(res => {
      console.log("createConnect", res)
    })
  },
  startDiscovery() {
    this.scale.startDiscovery()
  },
  stopDiscovery() {
    Scale.stopDiscovery().then(res => {
      console.log("stopDiscovery", res)
    })
  },
  closeAdapter() {
    this.scale.closeAdapter()
  },
  openAdapter() {
    this.scale.openAdapter()
  },
  createConnect() {
    Scale.createConnect().then(res => {
      console.log("createConnect", res)
    })
  },
  onUnload() {
    Scale.stop().then(res => {
      console.log("stop", res)
    })
  },
  onLoad: function() {

    Scale.init({
      auto_connect: true,
      height: 165,
      gender: 1,
      birthday: "1998-7-11",
      // person_body_shape: 1,
      // person_goal: 2,
      //timeout: 3500,
      appid: "mpplugin",
      secret: "1c98652952a92301",
      /* bfw_report: true,
      mineral_salt_report: true,
      stand_weight_report: true,
      weight_control_report: true,
      fat_control_report: true,
      muscle_control_report: true, */
      //tipToast: false,
     /*  appid: "herbalifemp", //康宝莱appid
      secret: "c2882deddc2d9c95", */
      //delay_notification: 1000,
      //calc_type: 10,
      /* version: 4,
      reset_device_list: true, */
      //muscle_rate_report: true
      //overtime: 10000,
      /* broadcast_timer: 10000, */
      //use_broadcast_restart: false,
      /* use_scale_unit: true, */
      // flag: true,
      //broadcast_timer: 1000
      /* url: "https://api.dev.pajkdc.com/m.api?_mt=healthIot.upScaleData",
      "header": {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
        "Cookie": "_tk=%2BSYfy94bRTEIEdq9WSzd6AohfHkGNLquwiWswxlepB735IV8lFsxZ44Fw2O9cybJ41CgODQBAxRcjCW8yup0rpihdgs15u9l3RT%2BKo4nWl0%3D;_wtk=ccad6047ad6e59580eb68cf686c6a7b4"
      },
      params: {
        height: 170,
        gender: 1,
        birthday: "1998-6-11",
        "_sm": "md5",
        "familyId": "test",
        "deviceSku": "sku",
        //"data": "{\"hexString\":\"D8588ED20AFE8A8C8FDC82BAA3DEAE8CDE984E94\"}",
        "_sig": "0b01d2c04494d470564e7fb21847beb3"
      } */
      log: wx.getLogManager
    }, data => {
      let { code, msg, bleState, state, realTimeWeight, devices, unit, err } = data

      if (code && msg) {
        console.log(code, msg)
      }

      if (devices != undefined) {
        console.log("devices", devices)
        this.setData({
          list: devices
        })
      }
      if (code == -1) {
        console.log('err', err)
      }
      if (code >= 1003 && code <= 1009) {
        if (realTimeWeight != undefined) {
          //console.log("realTimeWeight", realTimeWeight)
          this.setData({
            realTimeWeight,
            unit
          })
        }
        if (state) {
          this.setData({
            state
          })
        }
        this.setData({
          bleState
        })
      } else if (code == 1010) {
        console.log("data.result", data)
        if (data.result.length) {
          let obj = Scale.formatItemData(data.result)
          obj.birthday = "1990-01-01"
          obj.height = 170
          obj.gender = 1
          Scale.reportData(obj).then(d => {

            this.setData({
              bleState,
              state,
              score: 0,//data.result.score,
              measureData: d
            })
          })
        } else {
          this.setData({
            bleState,
            state,
            score: data.result.score,
            measureData: data.result
          })
          console.log("impedance", data.impedance)
        }
      } else if (code == 1013) {
        this.setData({
          state,
          bleState
        })
      } else if (code == 10003) {
        this.setData({
          state,
          bleState
        })
      }
    })
    //this.scale.openAdapter()
    //this.scale.startScan()
    Scale.start()
    console.log('Scale', Scale)

    Scale.up = log => {
      wx.request({
        method: 'post',
        url: 'http://192.168.2.65:5566/up',
        data: {
          result: log
        },
        success: res => {
          console.log('res', res)
        }
      })
    }
    Scale.onRequest = ({ hexString, inquiry }) => {

      if (inquiry) {
        //心率秤首次请求
        wx.request({
          method: 'post',
          url: 'http://192.168.2.65:5566/1',
          data: {
            hexString,
            inquiry
          },
          success: res => {
            let obj = {
              inquiry,
              ...res.data.data
            }
            console.log('res1', obj)
            Scale.requestEnd(obj)
          }
        })

      } else {
        wx.request({
          method: 'post',
          url: 'http://192.168.2.65:5566/1',
          data: {
            hexString
          },
          success: res => {
            console.log('res2', res)
            Scale.requestEnd(res.data.data)
          }
        })
      }
    }

    return

    this.scale = Scale.init({
      appid: "mpplugin",
      secret: "1c98652952a92301",
      height: 170,
      gender: 1,
      birthday: "1990-01-01",
      overtime: 6000,
      //蓝牙设备状态监听
      onAdapterStateChange: (available, discovering) => {

        this.setData({
          available,
          discovering
        })

        if (!available) {
          this.setData({
            bleState: "请打开蓝牙",
            state: "paused"
          })
        } else {
          this.setData({
            bleState: "空闲",
            state: "paused"
          })
        }

        console.log("onAdapterStateChange", available, discovering, this.data.connected)

        if (available && !discovering && !this.data.connected) {

          this.scale.startDiscovery()

        }

      },
      //扫描到的设备列表
      onDeviceScan: deviceList => {
        this.setData({
          list: deviceList
        })
      },
      //连接状态监听
      onConnectStateChange: (deviceId, connected) => {
        console.log("onConnectStateChange", connected)
        this.setData({
          connected
        })
        if (!connected) {
          this.setData({
            bleState: "空闲",
            state: "paused"
          })
        }
      },
      onConnectStatus: () => {
        this.setData({
          bleState: "正在连接",
          state: "paused"
        })
      },
      //收到的时时体重
      onWeight: weight => {
        console.log("weight", weight)
        if (weight === 0) {
          this.setData({
            bleState: "请赤脚轻踩上秤",
            state: "paused",
            realTimeWeight: weight
          })
        } else {
          this.setData({
            bleState: "正在测量",
            state: "running",
            realTimeWeight: weight
          })
        }
      },
      onStartFetch: () => {
        console.log("计算体质数据")
      },
      //测量完成
      onMeasureResult: res => {
        console.log("onMeasureResult", res)
      },
      //错误状态监听，会返回微信的错误码
      onError: err => {
        console.log("onError", err)
      }
    })

    this.scale.startScan()

    console.log("scale", this.scale)
   
    return
    this.scale = new Scale({
      //蓝牙设备状态监听
      onAdapterStateChange(available, discovering) {
        console.log("onAdapterStateChange", this, available, discovering)
        if (available && !discovering) {
          //this.scale.startScan()
        }

      },
      //扫描到的设备列表
      onDeviceScan: deviceList => {
        this.setData({
          list: deviceList
        })

      },
      //连接状态监听
      onConnectStateChange(deviceId, connected) {
        console.log("onConnectStateChange", deviceId, connected)
      },
      //收到的时时体重
      onGetRealTimeWeight(weight) {
        console.log("weight", weight)
      },
      /* onStartFetch() {
        console.log("计算体质数据")
      }, */
      //测量完成
      onSteadyData({ scaleString, weight, hasResistance, invalid_id }) {
        console.log("onSteadyData", arguments)
      },
      //连接错误状态监听，会返回微信的错误码
      onConnectError(err) {
        console.log("onConnectError", err)
      }
    })
    
    this.scale.startScan()

    console.log(this.scale)
  },
  stop() {
    Scale.stop().then(res => {
      console.log("stop", res)
    })
  },
  onHide() {

  },
  onShow() {
    let obj = {
      birthday: "1987-09-13",
      weight: 50.85,
      bmi: 19.1,
      height: 163,
      gender: 0,
      bodyfat: 16.8,
      water: 57.9,
      protein: 18.32,
      bmr: 1568,
      bodyAge: 24,
      bodyShape: 4,
      bone: 2.6,
      muscle: 55.7,
      subfat: 15.8,
      lbm: 41.56,
      visfat: 6,
      heartRate: 61,
      heartIndex: 3.5,
      muscleMass: 36.45
    }
    /* obj = {
      birthday: "1990-01-01",
      weight: 60,
      bmi: 20.6,
      height: 170,
      gender: 1,
      bodyfat: 12.8,
      water: 0,
      protein: 12.3,
      bmr: 20,
      bodyAge: 22,
      bodyShape: 0,
      bone: 2,
      muscle: 0,
      subfat: 0,
      lbm: 0,
      visfat: 0,
      heartRate: 0,
      heartIndex: 0,
      muscleMass: 0
    } */
    /* let list = [{ "type": 1, "value": 66.80 }, { "type": 2, "value": 22.60 }, { "type": 3, "value": 15.40 }, { "type": 4, "value": 13.60 }, { "type": 5, "value": 5 }, { "type": 6, "value": 61.10 }, { "type": 7, "value": 54.70 }, { "type": 8, "value": 2.83 }, { "type": 9, "value": 1590.00 }, { "type": 10, "value": 4 }, { "type": 11, "value": 19.25 }, { "type": 12, "value": 56.55 }, { "type": 13, "value": 53.69 }, { "type": 14, "value": 25 }, { "type": 16, "value": 102.00 }, { "type": 17, "value": 4.10 }]
    
    obj = Scale.formatItemData(list)

    obj.birthday = "1990-01-01"
    obj.height = 170
    obj.gender = 1 */
    console.log('dd', Scale.deepReport(obj))
    //console.log('dd', JSON.stringify(Scale.deepReport(obj)))
    Scale.reportData(obj, {
      muscle_rate_report: true,
      //unit: '斤',
      /* bfw_report: true,
      mineral_salt_report: true,
      stand_weight_report: true,
      weight_control_report: true,
      fat_control_report: true,
      muscle_control_report: true, */
    }).then(data => {
      console.log('show data', data)
      this.setData({
        measureData: data
      })
    })

    
    
  },
  restart() {
    Scale.restart()
  }
})